import { ref, reactive, onMounted } from "vue";
import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import { useRoute } from "vue-router";
import { useRouter } from "vue-router";
import {
  UserCreditScoringList, AddUserCreditScoring
  , QueryScoreResult, GetAddUserCreditScoringBaseData,
  QueryUserCreditScoringDetail
} from "@/api/stu/bankBigData";
export function usePortrait() {
  const detailData = ref()
  const dataList = ref();
  const route = useRoute();
  const router = useRouter();
  const customerNameRegex = /^[\u4e00-\u9fa5\w]{0,20}$/
  const createTaskVisible = ref<boolean>(false);
  const resultVisible = ref<boolean>(false);
  const showVisible = ref<boolean>(false);
  const resultList = ref()
  //定义的ref方便获取对应的子组件数据
  const PersonalStability = ref(null)
  //四个选择器List
  const productTypeList = ref()
  const customerList = ref()
  const preferentialItemList = ref()
  const preferentialScaleList = ref()
  const indexSystemList = ref()
  const modeData = reactive({
    fieldInfoDatas: []
  })
  const loading = ref<boolean>(false);
  const formData = reactive({
    creditModelName: '',
    productType: '',
    creditScoreUserGroupId: '',
    indexSystem: '',
  })

  const prefsorList = ref([{
    preferentialItem: '',
    minPreferentialScore: '',
    maxPreferentialScore: '',
    preferentialScale: '',
  }])
  const showData = reactive({
    creditModelName: '',
    productType: '',
    creditScoreUserGroupId: '',
    indexSystem: '',
  })
  const selectId = ref()
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [5, 10, 15],
    background: true
  });
  const pagination1 = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [5, 10, 15],
    background: true
  });
  const resultColumn: TableColumnList = [
    {
      label: "序号",
      type: "index",
      width: 120
    },
    {
      label: "客户群",
      prop: "name",
    },
    {
      label: "评分模型名称",
      prop: "creditModelName"
    },
    {
      label: "产品类型",
      prop: "productType",
    },
    {
      label: "信用评分结果",
      prop: "scoreResult",
    },
  ];
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      width: 120
    }, {
      label: "评分模型名称",
      prop: "creditModelName"
    }, {
      label: "产品类型",
      prop: "productType",
    },
    , {
      label: "客户群",
      prop: "customerGroupName",
    },
    {
      label: "操作",
      prop: "operation",
      width: 300,
      slot: "operation"
    },
  ];
  const BtnLoading = ref<boolean>(false)
  function OUTBtnLoding() {
    setTimeout(() => {
      BtnLoading.value = false
    }, 1000)
  }
  const handleCurrentChange = val => {
    getList()
  };
  function handleSizeChange() {
    getList()
  }
  const handleCurrentChange1 = val => {
    getList2()
  };
  function handleSizeChange1() {
    getList2()
  }

  //获取任务列表
  async function getList() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
    };
    const respone = await UserCreditScoringList(data);
    if (respone.success) {
      respone.data?.items.forEach(item => {
        item.createTime = item.createTime.substring(0, 10)
      })
      dataList.value = respone?.data.items
      pagination.total = respone.data.totalCount;
    } else {
      ElMessage.error(respone.msg);
    }
  }

  async function getList2() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination1.currentPage,
      pageCount: pagination1.pageSize,
      detailId: selectId.value,
    };
    const respone = await QueryScoreResult(data);
    if (respone.success) {
      resultVisible.value = true
      resultList.value = respone?.data.items
      pagination1.total = respone.data.totalCount;
    } else {
      ElMessage.error(respone.msg);
    }
  }
  async function checkPor(row) {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      detailId: row.creditScoreModelId,
    };
    const res = await QueryUserCreditScoringDetail(data);
    if (res.success) {
      showData.indexSystem = res?.data[0].portraitIndexSystemId
      showData.creditModelName = res?.data[0].creditModelName
      showData.creditScoreUserGroupId = res?.data[0].creditScoreUserGroupId
      showData.productType = res?.data[0].productType
      prefsorList.value = res?.data[0].preferentials
      detailData.value = res?.data[0].modelInfos
      setTimeout(() => {
        showVisible.value = true
      }, 100)
    } else {
      ElMessage.error(res.msg);
    }
  }
  //点击查看详情更新子列表
  async function checkResultList(row) {
    selectId.value = row.creditScoreModelId
    getList2()
  }
  onMounted(async () => {
    let data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    let res = await GetAddUserCreditScoringBaseData(data)
    if (res.success) {
      productTypeList.value = res?.data.dictionaryInfo.filter(item => item.dicValue == 'ProductType')[0].childrens
      preferentialItemList.value = res?.data.dictionaryInfo.filter(item => item.dicValue == 'PreferentialItem')[0].childrens
      preferentialScaleList.value = res?.data.dictionaryInfo.filter(item => item.dicValue == 'PreferentialScale')[0].childrens
      indexSystemList.value = res?.data.dictionaryInfo.filter(item => item.dicValue == 'IndexSystems')[0].childrens
      customerList.value = res?.data.dictionaryInfo.filter(item => item.dicValue == 'UserGroup')[0].childrens
      modeData.fieldInfoDatas = res?.data.fieldInfos
    } else {
      ElMessage.error(res.msg);
    }
    getList()
  })

  //提交数据新建
  async function SubmitVisible() {
    if (customerNameRegex.test(formData.creditModelName) == false) {
      ElMessage.warning('模型名称应输入20以内的字符')
      return
    }
    if (Number(formData.minPreferentialScore) < 0 || Number(formData.minPreferentialScore) > 10) {
      ElMessage.warning("最小值应在0到10之间");
      return
    } else if (Number(formData.maxPreferentialScore) < 0 || Number(formData.maxPreferentialScore) > 10) {
      ElMessage.warning("最大值应在0到10之间");
      return
    } else if (Number(formData.minPreferentialScore) > Number(formData.maxPreferentialScore)) {
      ElMessage.warning("最小值不应大于最大值");
      return
    }
    const resultParams = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      modelParamValues: [],
      creditModelName: formData.creditModelName,
      productType: formData.productType,
      creditScoreUserGroupId: formData.creditScoreUserGroupId,
      PortraitIndexSystemId: formData.indexSystem,
      preferentials: prefsorList.value,
    }
    let sum = 0
    PersonalStability.value.tableList.forEach(item => {
      sum += Number(item.indicatorWeight)
      var extractedData = {
        "apiFieldInfoId": item.apiFieldInfoId,
        "dataField": item.dataField,
        "evaluationCriterionList": [],
        "indicatorWeight": item.indicatorWeight,
      };
      //dataSetType 1是从大到小  2是从小到大  3是单选 4是多选
      if (item.dataSetType == 1) {
        const selectList = item.column.map(item => item.value).join(',');
        const evaluationCriterionList = [
          { evaluationCriterion: 3 },
          { evaluationCriterion: 5 },
          { evaluationCriterion: 8 },
          { evaluationCriterion: 10 }
        ];
        console.log(selectList.split(",").slice(0, 4));

        selectList.split(",").slice(0, 4).forEach((value, index) => {
          evaluationCriterionList[index].leftNumericalValue = Number(value);
          evaluationCriterionList[index].rightNumericalValue = Number(selectList.split(",")[index + 1]);
        });
        extractedData.evaluationCriterionList.push(...evaluationCriterionList);
      }
      if (item.dataSetType == 2) {
        const selectList = item.column.map(item => item.value).join(',');
        const evaluationCriterionList = [
          { evaluationCriterion: 3 },
          { evaluationCriterion: 5 },
          { evaluationCriterion: 8 },
          { evaluationCriterion: 10 }
        ];
        selectList.split(",").slice(0, 4).forEach((value, index) => {
          evaluationCriterionList[index].leftNumericalValue = Number(value);
          evaluationCriterionList[index].rightNumericalValue = Number(selectList.split(",")[index + 1]);
        });
        extractedData.evaluationCriterionList.push(...evaluationCriterionList);
      }
      if (item.dataSetType == 3) {
        let arr = item.column.map(item => item.value);
        const evaluationCriterionList = [
          { evaluationCriterion: 3, textTypeValue: arr[0] },
          { evaluationCriterion: 5, textTypeValue: arr[1] },
          { evaluationCriterion: 8, textTypeValue: arr[2] },
          { evaluationCriterion: 10, textTypeValue: arr[3] }
        ];
        extractedData.evaluationCriterionList.push(...evaluationCriterionList);
      }
      if (item.dataSetType == 4) {
        let arr = item.column.map(item => item.value.join('|'));
        const evaluationCriterionList = [
          { evaluationCriterion: 3, textTypeValue: arr[0] },
          { evaluationCriterion: 5, textTypeValue: arr[1] },
          { evaluationCriterion: 8, textTypeValue: arr[2] },
          { evaluationCriterion: 10, textTypeValue: arr[3] }
        ];
        extractedData.evaluationCriterionList.push(...evaluationCriterionList);
      }
      resultParams.modelParamValues.push(extractedData)
    })
    if (sum != 100) {
      ElMessage.warning('指标权重总和应该为100');
      return
    }
    resultParams.studentAnswer = JSON.stringify(resultParams)
    BtnLoading.value = true;
    OUTBtnLoding()
    let res = await AddUserCreditScoring(resultParams)
    if (res.status == 200) {
      ElMessage.success(res.msg);
      CloseVisible()
    } else {
      ElMessage.error(res.msg);
    }
  }

  function addLevel() {
    if (prefsorList.value.length == 4) {
      ElMessage.warning('最多只能创建四个优惠策略')
      return
    }
    prefsorList.value.push({
      preferentialItem: '',
      minPreferentialScore: '',
      maxPreferentialScore: '',
      preferentialScale: '',
    })
  }


  function deleteItem(index) {
    if (prefsorList.value.length == 1) {
      ElMessage.warning('至少保留一个优惠策略')
    } else {
      prefsorList.value.splice(index, 1)
    }
  }


  function CloseVisible() {
    createTaskVisible.value = false
    showVisible.value = false
    for (let variable in formData) {
      formData[variable] = '';
    }
    prefsorList.value = []
    prefsorList.value.push({
      preferentialItem: '',
      minPreferentialScore: '',
      maxPreferentialScore: '',
      preferentialScale: '',
    })
    getList()
  }
  return {
    columns,
    loading,
    dataList,
    pagination,
    formData,
    createTaskVisible,
    handleSizeChange,
    handleCurrentChange,
    productTypeList,
    customerList,
    preferentialItemList,
    preferentialScaleList,
    modeData,
    BtnLoading,
    SubmitVisible,
    PersonalStability,
    resultColumn,
    resultVisible,
    resultList,
    handleSizeChange1,
    handleCurrentChange1,
    pagination1,
    checkResultList,
    checkPor,
    prefsorList,
    showVisible,
    showData,
    detailData,
    addLevel,
    deleteItem,
    indexSystemList,
    CloseVisible
  }
}
